var dictTypeArray = [];

layui.config({
	base: '../'
}).use(['table','layer','form','util', 'treeTable'], function(){
	var table = layui.table;
	var layer = layui.layer;
	var form=layui.form
		, $ = layui.jquery;
	var util = layui.util;
	var treeTable = layui.treeTable;

	let insTb = null;

	$.ajax({
		url:"/cddatadict/type",
		type:'get',
		async:false,
		success:function(data){
			var type = data.resultContent;
			var obj;
			for(var i in type){
				$("#typeId").append("<option value='"+type[i].id+"'>"+type[i].typeName +"</option>");
				obj = {"id":type[i].id, "name":type[i].typeName};
				dictTypeArray.push(obj);
			}
			form.render();
			let typeId = $("#typeId").val();
			insTb = renderTable(typeId);
			showDeleteOrNot(typeId);
		}
	});


	$('body').removeClass('layui-hide');

	$(".layui-select-title input").on("focus",function(){
		$(this).val("");
	});

	function renderTable(typeId) {
		return treeTable.render({
			elem: '#dictAction',
			toolbar: '#toolbarDemo',
			// url:  "/cddatadict/dicts2",
			// where:{dictType :typeId},
			tree: {
				iconIndex: 2
			},
			cols: [[ //表头
				//,{field: 'id', title: 'ID',hide:true}
				{type:'numbers'},
				{type: 'checkbox'},
				{field: 'dictName', title: '字典名称', align:'center'}
				,{field: 'dictTypeName', title: '字典类型', align:'center'}
				,{field: 'dictKey', title: '字典键值', align:'center'}
				,{field: 'enableItem', title: '启用状态', align:'center'}
				,{field: 'dictReadme', title: '说明', align:'center'}
				,{field: 'createTime', title: '创建时间', sort: true, align:'center',width:160,templet:
						function(data){
							return data.createTime.split("T")[0];
						} }
				, {field: 'right', title: '操作', align:'center',width:200,templet:function(data){
						return '<div><a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="addSub">添加子项</a>' +
							'<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>' +
							'<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a></div>';
					}
				}
			]],
			reqData: function (data, callback) {
				// 懒加载也可以用url方式，这里用reqData方式演示
				let dictType = data ? data.id : typeId;
				$.get('/cddatadict/dicts2?dictType='+dictType, function (res) {
					callback(res.data);
				});
			},
			style: 'margin-top:0;'
		});
	}

	function openCreateItem() {
		$("#dictLayer").val(1);
		$("#dictTypeId").val($("#typeId").val());
		$("#dictTypeName").val($("#typeId").find("option:selected").text());
		$("#generateDictItemAciton")[0].reset();
		createDiv = layer.open({
			type: 1,
			title: "添加字典项",
			offset: '100px',
			skin: 'demo-class',
			closeBtn: 1,
			shift: 2,
			area: ['700px', '400px'],
			shadeClose: true,
			content: $("#generateItemType-main"),
		});
	}

	//头工具栏事件
	treeTable.on('toolbar(dictAction)', function(obj){
		//var checkStatus = treeTable.checkStatus(obj.config.id);
		let data = [];
		insTb.checkStatus().map(function (d) {
			data.push(d);
		});
		switch(obj.event){
			case 'addDictItem'://添加字典项
				openCreateItem();
				break;
			// case 'delDictItem'://删除字典项
			// 	delDictItem(data);
			// 	break;
			case 'btnExpandAll'://展开全部
				insTb.expandAll();
				break;
			case 'btnFoldAll'://折叠全部
				insTb.foldAll();
				break;
		}
	});

	function delDictItem(data) {
		if(data.length == 0){
			layer.msg("请选择要删除的字典项",{icon:5});
			return false;
		}
		layer.confirm('确定要删除选中的字典项吗?',function(){
			var loadIndex = layer.load();
			$.ajax({
				type: 'post',
				url: '/cddatadict/batchDelItem',
				contentType: "application/json;charset=utf-8",
				dataType: 'json',
				data: JSON.stringify(data),
				success: function (res) {
					layer.close(loadIndex);
					if(res.status == 200){
						layer.msg(res.msg,{icon:1});
						renderTable($("#typeId").val());
					}else {
						layer.msg(res.msg,{icon:5});
					}
				},
			});

		});

	}

	//监听工具条
	treeTable.on('tool(dictAction)', function(obj){
		var data = obj.data;
		switch(obj.event){
			case 'addSub':
				toAddSub(data);
				break;
			case 'edit':
				editItem(data);
				break;
			case 'del':
				delItem(data);
				break;
		}
	});

	function toAddSub(data) {
		$("#dictLayer").val(Number(data.dictLevel)+1);
		$("#dictTypeId").val(data.id);
		$("#dictTypeName").val(data.dictTypeName);
		$("#generateDictItemAciton")[0].reset();
		createDiv = layer.open({
			type: 1,
			title: "添加字典子项",
			offset: '100px',
			skin: 'demo-class',
			closeBtn: 1,
			shift: 2,
			area: ['700px', '400px'],
			shadeClose: true,
			content: $("#generateItemType-main"),
		});
	}

	function editItem(data) {
		$('#itemName-update').val(data.dictName);
		$('#itemDesc-update').val(data.dictReadme);
		$('#itemKey-update').val(data.dictKey);
		$('#itemType-update').val(data.dictType);
		$('#itemId-update').val(data.id);
		$('#dictLayer2').val(data.dictLevel);
		$('#dictTypeName2').val(data.dictTypeName);
		$('#dictCode2').val(data.dictCode);
		$('#dictAttribute2').val(data.dictAttribute);
		$('#dictRemark2').val(data.dictRemark);
		$("#isChecked").empty();
		if (data.enableItem == "yes") {
			$("#isChecked").append('<input type="radio" name="enable" value="yes" title="yes" checked>' +
				'<input type="radio" name="enable" value="no" title="no">')
		} else {
			$("#isChecked").append('<input type="radio" name="enable" value="yes" title="yes">' +
				'<input type="radio" name="enable" value="no" title="no" checked>')
		}
		form.render("radio");
		updateDiv = layer.open({
			type: 1,
			title: "编辑字典项",
			offset: '100px',
			skin: 'demo-class',
			closeBtn: 1,
			shift: 2,
			area: ['700px', '450px'],
			shadeClose: true,
			content: $("#updateDictItem-main"),
		});
	}

	function delItem(data) {
		layer.confirm('确定要删除该数据么',function(){
			$.post("/cddatadict/dicts/delete",{"dictId":data.id}, function( data ) {
				if(data.resultDesc=="OK"){
					layer.msg('删除成功',{icon:1});
					renderTable($("#typeId").val());
					showDeleteOrNot($('#typeId').val());
				}else{
					layer.msg(data.resultDesc,{icon:5});
				}
			});

		});
	}

	form.on('submit(generateDictTypeAciton)', function(data){
		createType();
		return false;
	});

	form.on('submit(updateDictTypeAciton)', function(data){
		updateType();
		return false;
	});

	form.on('submit(generateDictItemAciton)', function(data){
		ajaxCreateItem();
		return false;
	});

	form.on('submit(updateDictItemAciton)', function(data){
		updateItem();
		return false;
	});

	function createType(){
		var url = '/cddatadict/type/add';
		var typeName = $('#typeName').val();
		var typeDesc = $('#typeDesc').val();
		if(checkData()){
			$.ajax({
				url: url,
				data: {
					typeName: typeName,
					typeDesc: typeDesc
				},
				dataType: 'json',
				type: 'post',
				success: function(data){
					layer.closeAll();
					resetFrom($("#generateDictTypeAciton"), true, typeName);
					if(data.resultDesc == 'OK'){
						layer.alert('成功！！',{
							title:"",
							icon: 1,
							btn:"",
							time:2000,
							shift:6,
							closeBtn: 0
						});

						$("#reload").click();
					}
					if(data.resultDesc == "isExist"){
						layerAlter('该字典类型已存在！！');
					}
				},
				error : function(data){
					layer.closeAll();
					resetFrom($("#generateDictTypeAciton"))
					layerAlter('创建字典类型失败！！');
				}
			});
		}
	}

	function updateType(){
		var url = '/cddatadict/type/update';
		var typeName = $('#typeName-update').val();
		var typeDesc = $('#typeDesc-update').val();
		var typeId = $("#typeId").val();
		var enable;
		if($("#isCheckedType input[type='radio']:checked").val() == "yes"){
			enable = "yes";
		}else{
			enable = "no";
		}

		if(checkData()){
			$.ajax({
				url: url,
				data: {
					id : typeId,
					typeName : typeName,
					typeReadme : typeDesc,
					enableType : enable
				},
				dataType: 'json',
				type: 'post',
				success: function(data){
					layer.closeAll();
					resetFrom($("#updateDictTypeAciton"), true, typeName);
					if(data.resultDesc == 'OK'){
						layer.alert('成功！！',{
							title:"",
							icon: 1,
							btn:"",
							time:2000,
							shift:6,
							closeBtn: 0
						});
						$("#reload").click();
					}
					if(data.resultDesc == "nameIsExist"){
						layerAlter('该字典类型名称已存在！！');
					}
				},
				error : function(data){
					layer.closeAll();
					resetFrom($("#updateDictTypeAciton"))
					layerAlter('更新字典类型失败！！');
				}
			});
		}
	}

	function ajaxCreateItem() {
		var url = '/cddatadict/dicts/add';
		var itemName = $('#itemName').val();
		var itemDesc = $('#itemDesc').val();
		var itemKey = $('#itemKey').val();
		var dictCode = $('#dictCode').val();
		var dictAttribute = $('#dictAttribute').val();
		var dictRemark = $('#dictRemark').val();
		var dictLevel = Number($('#dictLayer').val());
		var itemType = $("#dictTypeId").val();
		var itemTypeName = $("#typeId").find("option:selected").text();
		if (checkData()) {
			$.ajax({
				url: url,
				data: {
					dictType: itemType,
					dictTypeName: itemTypeName,
					dictName: itemName,
					dictKey: itemKey,
					dictReadme: itemDesc,
					dictLevel: dictLevel,
					dictCode: dictCode,
					dictAttribute: dictAttribute,
					dictRemark: dictRemark
				},
				dataType: 'json',
				type: 'post',
				success: function (data) {
					if (data.resultDesc == 'OK') {
						layer.alert('成功！！', {
							title: "",
							icon: 1,
							btn: "",
							time: 2000,
							shift: 6,
							closeBtn: 0
						});
						var dictLayer = $("#dictLayer").val();
						layer.close(createDiv);
						renderTable($("#typeId").val())
						resetFrom($("#generateDictItemAciton"), false, itemType);
						showDeleteOrNot($("#typeId").val());
					}
					if (data.resultDesc == "nameIsExist") {
						layerAlter('该字典名称已存在！！');
					}
					if (data.resultDesc == "keyIsExist") {
						layerAlter('该字典键值已存在！！');
					}
				},
				error: function (data) {
					resetFrom($("#generateDictItemAciton"))
					layerAlter('创建字典值失败！！');
				}
			});
		}
	}

	function updateItem(){
		var url = '/cddatadict/dicts/update';
		var itemName = $('#itemName-update').val();
		var itemDesc = $('#itemDesc-update').val();
		var itemKey = $('#itemKey-update').val();
		var itemId = $("#itemId-update").val();
		var itemType = $("#itemType-update").val();
		var dictCode = $("#dictCode2").val();
		var dictAttribute = $("#dictAttribute2").val();
		var dictRemark = $("#dictRemark2").val();
		var dictLevel = Number($('#dictLayer2').val());
		var enable;
		if($("#isChecked input[type='radio']:checked").val() == "yes"){
			enable = "yes";
		}else{
			enable = "no";
		}
		if(checkData()){
			$.ajax({
				url: url,
				data: {
					id : itemId,
					dictType: itemType,
					dictName : itemName,
					dictReadme : itemDesc,
					dictKey : itemKey,
					enableItem : enable,
					dictLevel : dictLevel,
					dictCode : dictCode,
					dictAttribute : dictAttribute,
					dictRemark : dictRemark
				},
				dataType: 'json',
				type: 'post',
				success: function(data){
					if(data.resultDesc == 'OK'){
						layer.alert('更新成功！！',{
							title:"",
							icon: 1,
							btn:"",
							time:2000,
							shift:6,
							closeBtn: 0
						});
						layer.close(updateDiv);
						renderTable($("#typeId").val())
						resetFrom($("#updateDictItemAciton"), false, "");
					}
					if(data.resultDesc == "nameIsExist"){
						layerAlter('该字典名称已存在！！');
					}
					if(data.resultDesc == "keyIsExist"){
						layerAlter('该字典键值已存在！！');
					}
				},
				error : function(data){
					resetFrom($("#updateDictItemAciton"))
					layerAlter('更新字典值失败！！');
				}
			});
		}
	}

	function checkData(){
//		var pattern = /^[0-9].*$/;
//		if($('#typeName').val() != undefined && $('#typeName').val().length > 0){
//			if(!pattern.test($('#typeName').val())){
//				
//				layerAlter("请输入正确的高层价格！！");
//				return false;
//			}
//		}else{
//			$('#typeName').val(0);
//		}
//		if($('#typeName').val() != undefined && $('#typeName').val().length > 0){
//			if(!pattern.test($('#typeName').val())){
//				
//				layerAlter("请输入正确的高层价格！！");
//				return false;
//			}
//		}else{
//			$('#typeName').val(0);
//		}

		return true;

	}

	let createDiv,updateDiv;

	var $ = layui.$,
		active = {
			reload: function(){
				var typeId = $('#typeId').val();
				//执行重载
				table.reload('dictAction', {
					page: {
						curr: 1 //重新从第 1 页开始
					},
					where: {
						dictType: typeId,
					},
					done: function(){
						if(typeId.length == 0){
							$("#addDictItem").addClass('layui-btn-disabled');
							$("#addDictItem").attr('disabled','true');
							$("#updateType").addClass('layui-btn-disabled');
							$("#updateType").attr('disabled','true');
						}else{
							$("#addDictItem").removeClass('layui-btn-disabled');
							$("#addDictItem").removeAttr('disabled');
							$("#updateType").removeClass('layui-btn-disabled');
							$("#updateType").removeAttr('disabled');
						}
						$("#add2DictItem").addClass('layui-btn-disabled');
						$("#add2DictItem").attr('disabled','true');
						$(".layui-table-body tr").attr({"style":"background:#FFFFFF"});
					}
				});
			}
			,generateDictType:function(){

				layer.open({
					type: 1,
					title:"创建字典类型",
					offset: '100px',
					skin:'demo-class',
					closeBtn: 1,
					shift: 2,
					area: ['380px', '280px'],
					shadeClose: true,
					content: $("#generateDictType-main"),
				});
			}
			,updateType:function(){
				layer.open({
					type: 1,
					title:"创建字典类型",
					offset: '100px',
					skin:'demo-class',
					closeBtn: 1,
					shift: 2,
					area: ['380px', '280px'],
					shadeClose: true,
					content: $("#updateDictType-main"),
				});

				var typeId = $('#typeId').val();
				$.ajax({
					url: '/cddatadict/type/id',
					data: {
						typeId : typeId
					},
					dataType: 'json',
					type: 'get',
					success: function(data){
						if(data.resultDesc == 'OK'){
							resultContent = data.resultContent;
							$('#typeName-update').val(resultContent.typeName);
							$('#typeDesc-update').val(resultContent.typeReadme);
							$("#isCheckedType").empty();
							if(resultContent.enableType == "yes"){
								$("#isCheckedType").append('<input type="radio" name="enable" value="yes" title="yes" checked>'+
									'<input type="radio" name="enable" value="no" title="no">')
							}else{
								$("#isCheckedType").append('<input type="radio" name="enable" value="yes" title="yes">'+
									'<input type="radio" name="enable" value="no" title="no" checked>')
							}
							form.render("radio");
						}
					},
					error : function(data){
						layer.closeAll();
//					resetFrom($("#generateBillsAciton"))
						layerAlter('获取字典信息失败！！');
					}
				});
			}

			,deleteType: function(){
				layer.confirm('确定要删除该数据么',function(){

					var typeId = $('#typeId').val();
					$.ajax({
						url: '/cddatadict/type/delete',
						data: {
							typeId : typeId
						},
						dataType: 'json',
						type: 'post',
						success: function(data){
							if(data.resultDesc == 'OK'){
								layer.msg('删除成功');
								location.reload();
							}else{
								layer.msg('删除失败');
							}
						},
						error : function(data){
							layer.msg('删除失败');
						}
					});

				});

			}

		};

	$('.query .layui-btn').on('click', function(){
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});

	function resetFrom($form, isResetType, typeName){
		$form.find('input[type=text],input[type=hidden]').each(function() {
			$(this).val('');
		});
		$form.find('dd').each(function(){
			$(this).removeClass('layui-this');
		});
		if(isResetType){
			$.ajax({
				url:"/cddatadict/type",
				type:'get',
				async:false,
				success:function(data){
					var type = data.resultContent;
					var typeId;
					dictTypeArray = [];
					var obj;
					$("#typeId").empty();
					//$("#typeId").append("<option value=''>请搜索或选择</option>");
					for(var i in type){
						if(type[i].typeName == typeName){
//		  					$("#typeId").append("<option value='"+type[i].id+"' checked>"+type[i].typeName +"</option>");
//		  					continue;
							typeId = type[i].id;
						}
						$("#typeId").append("<option value='"+type[i].id+"'>"+type[i].typeName +"</option>");
						obj = {"id":type[i].id, "name":type[i].typeName};
						dictTypeArray.push(obj);
					}
					form.render("select");
					var select = 'dd[lay-value=' + typeId + ']';
					$("div.layui-form-select").find('dl').find(select).click();
				}

			});
		}
	}

	form.on("select(typeId)",function(){
		var typeId = $('#typeId').val();
		showDeleteOrNot(typeId);
		insTb = renderTable(typeId);
	});

	function showDeleteOrNot(typeId) {
		//控制删除按钮是否显示
		$.ajax({
			url: '/cddatadict/dicts/typeId',
			data: {
				typeId : typeId
			},
			dataType: 'json',
			type: 'get',
			success: function(data){
				if(data && data.resultDesc == 'OK' && data.resultContent && data.resultContent > 0) {
					$("#deleteType").addClass('layui-btn-disabled');
					$("#deleteType").attr('disabled', 'true');
				}else{
					$("#deleteType").removeClass('layui-btn-disabled');
					$("#deleteType").removeAttr('disabled');
				}
			},
			error : function(){
				$("#deleteType").addClass('layui-btn-disabled');
				$("#deleteType").attr('disabled','true');
			}
		});
	}

	$("#uploadBtn").on("click",function(){
		$("#uploadFile").click();
	});
	$("#uploadFile").on("change",function(){
		var name = $(this).val();
		if(!name || name.substring(name.lastIndexOf(".")+1) !== "json"){
			layer.msg("请上传json文件！",{icon:5});
			return false
		}
		$("#upload_form").attr("disabled", false);
		$("#upload_form").removeClass("layui-btn-disabled");
		var index = name.lastIndexOf("\\")+1;
		$("#file_name").val(name.substring(index));
	});
	// 导入
	$("#import").on('click', function (){
		layer.open({
			type: 1
			,title: '上传文件'
			,area: ['45%','30%']
			,content: $('#upload')
		});
	});
	form.on('submit(upload_form)',function(){
		$("#upload_form").attr("disabled", true);
		$("#upload_form").attr("class", "layui-btn layui-btn-disabled");
		var formData = new FormData();
		formData.append("file",$("#uploadFile")[0].files[0]);
		layer.load();
		$.ajax({
			url:'/cddatadict/type/upload2',
			type: 'POST',
			data: formData,
			processData: false,
			contentType:false,
			success:function(res){
				if (res.status === 200) {
					layer.msg(res.msg,{icon: 1});
					setTimeout(function () {
						location.reload();
					},2000);
				}else {
					layer.msg(res.msg,{icon:5});
				}
				$("#uploadFile").val("");
				$("#file_name").val("");
				$("#upload_form").attr("disabled", false);
				$("#upload_form").attr("class", "layui-btn");
			}
		});
		return false;
	});

	// 导出
	$("#export").on('click', function () {
		// downloadFile("/cddatadict/type/export");
		downFileWithPath("/cddatadict/type/export2");
	});

	// 刷新
	$("#refresh").on('click', function (){
		location.reload();
	});
	// 全部删除
	$("#deleteAll").on('click', function (){
		layer.confirm('确定要全部删除吗?', {
		}, function(){
			layer.load();
			$.get('/cddatadict/deleteAll',{},function (res) {
				layer.msg(res.msg,{
					time:500,
					end:function () {
						location.reload();
						layer.closeAll();
					}
				});
			});
		});
	});

})
function reqType(type) {
	for(var i in dictTypeArray){
		if(type && dictTypeArray[i].id === type){
			return dictTypeArray[i].name;
		}
	}
	return "-";
}
function layerAlter(str){
	layer.alert(str,{
		title:"",
		icon: 2,
		btn:"",
		time:2000,
		shift:6,
		closeBtn: 0
	});
}
window.downloadFile = function (sUrl) {
	var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
	//iOS devices do not support downloading. We have to inform user about this.
	if (/(iP)/g.test(navigator.userAgent)) {
		return false;
	}
	//If in Chrome or Safari - download via virtual link click
	if (isChrome || isSafari) {
		//Creating new link node.
		var link = document.createElement('a');
		link.href = sUrl;
		//Dispatching click event.
		if (document.createEvent) {
			var e = document.createEvent('MouseEvents');
			e.initEvent('click', true, true);
			link.dispatchEvent(e);
			return true;
		}
	}
	window.open(sUrl, '_self');
	return true;
}

function downFileWithPath(path) {
	if (path) {
		var a = document.createElement('a');
		a.setAttribute('download', '');
		a.setAttribute('href', path);
		a.click()
	}
}
